import logging
from mcp.server.fastmcp import FastMCP
from mcp.types import TextContent

# 日志相关配置
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("calculation_mcp_server")

# 初始化 FastMCP 服务器
mcp = FastMCP("calculator")

# 使用mcp.tool()作为装饰器标记工具函数
@mcp.tool(name="add", description="计算两个数的和")
async def add(a: float, b: float) -> list[TextContent]:
    logger.info(f"Add operation: {a} + {b}")
    result = a + b
    return [TextContent(type="text", text=str(result))]

@mcp.tool(name="subtract", description="计算两个数的差")
async def subtract(a: float, b: float) -> list[TextContent]:
    logger.info(f"Subtract operation: {a} - {b}")
    result = a - b
    return [TextContent(type="text", text=str(result))]

@mcp.tool(name="multiply", description="计算两个数的积")
async def multiply(a: float, b: float) -> list[TextContent]:
    logger.info(f"Multiply operation: {a} * {b}")
    result = a * b
    return [TextContent(type="text", text=str(result))]

@mcp.tool(name="divide", description="计算两个数的商")
async def divide(a: float, b: float) -> list[TextContent]:
    logger.info(f"Divide operation: {a} / {b}")
    if b == 0:
        raise ValueError("除数不能为0")
    result = a / b
    return [TextContent(type="text", text=str(result))]

if __name__ == "__main__":
    print("计算服务器启动中...")
    try:
        # 使用标准输入输出作为传输方式
        mcp.run(transport='stdio')
    except KeyboardInterrupt:
        print("服务器已停止")